package net.alan.modules.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import net.alan.common.utils.StringUtils;
import net.alan.modules.bean.*;
import net.alan.modules.cache.WebContextUtil;
import net.alan.modules.handle.BaseExecption;
import net.alan.modules.service.IFavoriteService;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Author 李岩飞
 * Email eliyanfei@126.com
 * 2017/11/21
 */
@Api(tags = "收藏夹管理")
@Controller
@RequestMapping(value = "favorite")
public class FavoriteController extends BaseController {
    @Autowired
    private IFavoriteService favoriteService;

    @ApiOperation(value = "添加", notes = "")
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public Result add(String url, String title, Integer catalogId) throws Exception {
        User user = WebContextUtil.getCurrentUser().getUser();
        try {
            final Favorite favorite = new Favorite();
            favorite.setUserId(user.getId());
            Connection connection = Jsoup.connect(url);
            Document document = connection.get();
            if (StringUtils.isEmpty(title))
                title = document.title();
            String content = document.text();
            int lens = Math.min(content.length(), 100);
            content = content.substring(0, lens);
            favorite.setContent(content);
            favorite.setCatalogId(catalogId);
            favorite.setTitle(title);
            favorite.setUrl(url);
            favoriteService.save(Favorite.class,favorite);
        } catch (BaseExecption baseExecption) {
            return ResultUtil.error("保存异常");
        }
        return ResultUtil.success();
    }

    @ApiOperation(value = "添加目录", notes = "")
    @RequestMapping(value = "addcatalog", method = RequestMethod.POST)
    @ResponseBody
    public Result add(Integer id, String title) throws Exception {
        User user = WebContextUtil.getCurrentUser().getUser();
        try {
            FavoriteCatalog catalog = favoriteService.getById(FavoriteCatalog.class, id);
            if (catalog == null) {
                catalog = new FavoriteCatalog();
                catalog.setUserId(WebContextUtil.getUserId());
            }
            catalog.setTitle(title);
            favoriteService.save(FavoriteCatalog.class,catalog);
        } catch (BaseExecption baseExecption) {
            return ResultUtil.error("保存异常");
        }
        return ResultUtil.success();
    }

    @ApiOperation(value = "修改", notes = "")
    @RequestMapping(value = "edit", method = RequestMethod.POST)
    @ResponseBody
    public Result edit(Integer id, String title, Integer catalogId) throws Exception {
        User user = WebContextUtil.getCurrentUser().getUser();
        try {
            final Favorite favorite = favoriteService.getById(Favorite.class, id);
            favorite.setTitle(title);
            favorite.setCatalogId(catalogId);
            favoriteService.save(Favorite.class,favorite);
        } catch (BaseExecption baseExecption) {
            return ResultUtil.error("保存异常");
        }
        return ResultUtil.success();
    }

    @ApiOperation(value = "删除", notes = "")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer")
    @RequestMapping(value = "delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Result delete(@PathVariable("id") Integer id) throws Exception {
        Result result = null;
        try {
            result = favoriteService.delete(Favorite.class, id);
        } catch (BaseExecption baseExecption) {
            result = ResultUtil.error("删除异常");
        }
        return result;
    }

    @ApiOperation(value = "删除目录", notes = "")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer")
    @RequestMapping(value = "deletecatalog/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Result deleteCatalog(@PathVariable("id") Integer id) throws Exception {
        return favoriteService.deleteCatalog(id);
    }

    @ApiOperation(value = "获取单个收藏", notes = "")
    @ApiImplicitParam(name = "id", value = "Id", required = true, dataType = "Integer")
    @RequestMapping(value = "get/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Favorite get(@PathVariable("id") Integer id) throws Exception {
        return favoriteService.getById(Favorite.class, id).copy();
    }

    @ApiOperation(value = "获取目录", notes = "")
    @ApiImplicitParam(name = "id", value = "Id", required = true, dataType = "Integer")
    @RequestMapping(value = "getcatalog/{id}", method = RequestMethod.GET)
    @ResponseBody
    public FavoriteCatalog getCatalog(@PathVariable("id") Integer id) throws Exception {
        return favoriteService.getById(FavoriteCatalog.class, id).copy();
    }

    @ApiOperation(value = "列表")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public PageModel list(Integer catalogId, PageModel pageModel) throws Exception {
        Page<Favorite> list = null;
        if (catalogId == null || catalogId <= 0)
            list = this.favoriteService.findByUserId(WebContextUtil.getUserId(), pageModel);
        else
            list = this.favoriteService.findByCatalogId(catalogId, pageModel);
        return pageModel.toPageModel(list);
    }

    @ApiOperation(value = "目录列表")
    @RequestMapping(value = "listcatalog", method = RequestMethod.GET)
    @ResponseBody
    public List<FavoriteCatalog> listCatalog() throws Exception {
        return favoriteService.findCatalogByUserId(WebContextUtil.getUserId());
    }

    /**
     * 导出
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        try {
            response.reset();
            response.setContentType("bin");
            try {
                response.setHeader("Content-type", "text/csv; charset=utf-8");
                response.setHeader("Content-Disposition", "attachment; filename=\"export.html\"");
            } catch (Exception localUnsupportedEncodingException) {
            }
            PrintWriter ps = response.getWriter();
            ps.println("<!DOCTYPE NETSCAPE-Bookmark-file-1>");
            ps.println("<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">");
            ps.println("<TITLE>收藏夹</TITLE>");
            ps.println("<DL><p>");
            ps.println("<DT><H3  PERSONAL_TOOLBAR_FOLDER=\"true\">收藏夹</H3>");

            ps.println("<DL><p>");
            List<Favorite> list = favoriteService.findByUserId(WebContextUtil.getUserId());
            for (Favorite favorite : list) {
                ps.println("<DT><A HREF=\"" + favorite.getUrl() + "\">" + favorite.getTitle() + "</A>");
            }
            ps.println("</DL><p>");
            ps.println("</DL><p>");

            ps.flush();
            ps.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    /**
     * 导入
     */
    @RequestMapping(value = "import", method = RequestMethod.POST)
    @ResponseBody
    public Result doUploadFile(HttpServletRequest request)
            throws Exception, IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        try {
            Document document = Jsoup.parse(file.getInputStream(), "utf-8", "");
            Elements elements = document.getElementsByTag("a");
            Integer userId = WebContextUtil.getUserId();
            for (int i = 0; i < elements.size(); i++) {
                Element ele = elements.get(i);
                String url = ele.attr("HREF");
                if (url.length() > 200) continue;
                Favorite favorite = new Favorite();
                favorite.setContent(ele.text());
                favorite.setTitle(ele.text());
                favorite.setUserId(userId);
                favorite.setUrl(url);
                favoriteService.save(Favorite.class,favorite);
            }
        } catch (Exception baseExecption) {
            baseExecption.printStackTrace();
        } catch (BaseExecption baseExecption) {
            baseExecption.printStackTrace();
        }
        return ResultUtil.success();
    }

}
